import React, { useRef, useState } from "react";
import { Button, DatePicker, Form, Input, Space, Tabs } from "antd";
import CompanyListTable from "./CompanyListTable";
import { useComponentDidMount } from "@/hooks";
import CompanyUpdate from "../modals/CompanyUpdate";
import { addCompany, fetchCompanyTabNum } from '../services';
import { companyTypes } from "@/constants/types";

const {Item} = Form;

const AddCompanyBtn = ({onRefresh}: {onRefresh: any}) => {
  const [visible, setVisible] = useState(false);

  const companyAddProps = {
    title: '新增客户',
    visible,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: companyTypes) => {
      const res = await addCompany(params);
      if (res?.code === '0') {
        setVisible(false);
        onRefresh();
      }
    }
  }

  const handleAdd = () => {
    setVisible(true);
  }

  return (
    <>
      <Button type="primary" onClick={() => handleAdd()}>新增客户</Button>
      {visible && <CompanyUpdate {...companyAddProps} />}
    </>
  );
}

const CompanyList = () => {
  const [form] = Form.useForm();
  const noAuthRef = useRef();
  const authingRef = useRef();
  const authedRef = useRef();
  const [activeKey, setActiveKey] = useState<string>('noAuth');
  const [tabNum, setTabNum] = useState<any>({noAuth: 0, checkingNum: 0, authed: 0});
  const [searchValue, setSearchValue] = useState({});
  const initValues = {
    destType: '1'
  }

  const getParams = () => {
    const params = form.getFieldsValue();
    const maps: any = {
      all: undefined,
      noAuth: '0',
      checkingNum: '2',
      authed: '1'
    }
    return {
      ...params,
      checkTimeBegin: params?.checkTime?.[0]?.format('YYYY-MM-DD 00:00:00'),
      checkTimeEnd: params?.checkTime?.[1]?.format('YYYY-MM-DD 23:59:59'),
      checkStatus: maps?.[params?.activeKey],
      checkTime: undefined
    };
  }

  const fetchTabNum = async () => {
    const res = await fetchCompanyTabNum(getParams());
    setTabNum({
      noAuth: res?.waitCheckNum || 0,
      checkingNum: res?.checkingNum || 0,
      authed: res?.checkedNum || 0,
    });
  }


  const tabChange = (key: string) => {
    setActiveKey(key);
  }

  const refreshNum = () => {
    fetchTabNum();
  }

  const childrenProps: {refreshNum: any; activeKey: string; searchValue: any;} = {
    refreshNum,
    activeKey,
    searchValue
  }
  const tabList: Array<any> = [
    {
      title: '待认证',
      key: 'noAuth',
      label: tabNum?.noAuth > 0 ? `待认证 ( ${ tabNum?.noAuth} )` : '待认证',
      comRef: noAuthRef,
      children: <CompanyListTable {...childrenProps} tabKey="noAuth" ref={noAuthRef} />,
    },
    {
      title: '认证中',
      key: 'checkingNum',
      label: tabNum?.checkingNum > 0 ? `认证中 ( ${ tabNum?.checkingNum} )` : '认证中',
      comRef: authingRef,
      children: <CompanyListTable {...childrenProps} tabKey="checkingNum" ref={authingRef} />,
    },
    {
      title: '已认证',
      key: 'authed',
      label: tabNum?.authed > 0 ? `已认证 ( ${ tabNum?.authed} )` : '已认证',
      comRef: authedRef,
      children: <CompanyListTable {...childrenProps} tabKey="authed" ref={authedRef} />,
    },
  ];

  const search = () => {
    setTimeout(() => {
      const refObj = tabList.find(v => v.key === activeKey)?.comRef;
      refObj?.current?.refreshTable();
      fetchTabNum();
    }, 0)
  }
  const handleSearch = () => {
    setSearchValue(getParams());
    search();
  }
  const handleReset = () => {
    form.resetFields();
    setSearchValue({});
    search();
  }


  useComponentDidMount(() => {
    fetchTabNum();
  });
  
  return (
    <>
      <Form form={form} initialValues={initValues} layout="inline" >
        <Item name="checkTime" label="认证时间" style={{marginBottom: 15}}>
          <DatePicker.RangePicker />
        </Item>
        <Item name="nickName" label="公司简称" style={{marginBottom: 15}}>
          <Input />
        </Item>
        <Item name="mobile" label="手机号" style={{marginBottom: 15}}>
          <Input />
        </Item>
        <Item>
          <Space>
            <Button type="primary" onClick={handleSearch}>查询</Button>
            <Button type="default" onClick={handleReset}>重置</Button>
          </Space>
        </Item>
      </Form>
      <Tabs
        activeKey={activeKey}
        onChange={tabChange} 
        tabBarExtraContent={{
          right: <AddCompanyBtn onRefresh={() => {
            handleSearch();
          }} />
        }}
        items={tabList}
      />
    </>
  );
};


export default CompanyList;